#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
use Scalar::Util qw(looks_like_number);
 
use JSON;
use File::Copy;


sub die_nice {
    my ( $real_error ) = @_;
    warn $real_error;                 # this will log it like die
    my($msg) = @_;
    #print header();
    #print start_html("Error");
    print "Error\n";
    print $msg;
    exit;
}

sub loadPlayers 
{
	my $count=0;
	my $playerref = $_[0];
	my $playername = $_[1];
	my $playeralt = $_[2];
	my $altname="";
	my $realm=get_realm();
	open my $fh, "<:utf8", "data/players".".$realm" or die_nice("can't open PLAYERS".".$realm file to read $!");
    while (my $line = <$fh>) 
	{
		if ($line !~ /^#/) { # only read non commented lines
			my ($id,$name) = split( /\|/, $line);
			chomp($id);
			chomp($name);
			$count++;
			$altname=lc($name);
			$playerref->{$id}=$name;
			$playername->{$name}=$id;
			$playeralt->{$altname}=$id;
		}
	}
	close $fh;
	return ($count);
}

sub writePlayers
{
	my $count=0;
	my $playerref = $_[0];
	my $realm=get_realm();
	open my $fh, ">:utf8", "data/players".".$realm" or die_nice("can't open PLAYERS".".$realm file to write $!");
	foreach my $id (keys %{$playerref})
	{
	    $count++;
		print $fh "$id|$playerref->{$id}\n";
	}
	close $fh;
	return($count);
}

sub loadAlliance 
{
	my $count=0;
	my $alli_ref = $_[0];
	my $alliancename = $_[1];
	my $realm=get_realm();

	open my $fh, "<:utf8", "data/alliance".".$realm" or die_nice("can't open ALLIANCE".".$realm file to read $!"); 
    while (my $line = <$fh>) 
	{
		if ($line !~ /^#/) { # only read non commented lines
			my ($id,$name,$rank,$state,$lord,$members) = split( /\|/, $line);
			chomp($name);
			chomp($id);
			chomp($state);
			chomp($rank);
			chomp($lord);
			chomp($members);
			$count++;
			$alli_ref->{$id}={'name'=>$name, 'state'=>$state, 'rank'=>$rank, 'lord'=>$lord, 'members'=>$members};
			$alliancename->{$name}=$id;
		}
	}
	close $fh;
	return($count);
}

sub writeAlliance
{
	my $count=0;
	my $alli_ref = $_[0];
	my $realm=get_realm();
	open my $fh, ">:utf8", "data/alliance".".$realm" or die_nice("can't open ALLIANCE".".$realm file to write $!");
	foreach my $id (keys %{$alli_ref})
	{
	    $count++;
		print $fh "$id|$alli_ref->{$id}{'name'}|$alli_ref->{$id}{'rank'}|$alli_ref->{$id}{'state'}|$alli_ref->{$id}{'lord'}|$alli_ref->{$id}{'members'}\n";
	}
	close $fh;
	return ($count);
}

sub readDir
{
	my $directory=$_[0];
	opendir DIR, "$directory/"  or die_nice("can't find Directory $directory $!");
	my @files = grep { $_ ne '.' && $_ ne '..' } readdir DIR;
	closedir DIR;
	@files=sort(@files);
	return @files;
}

sub loadMAP
{
	my $fname=$_[0];
	my $realm=get_realm();
    my $fullname=$fname.".".$realm;
	return(readJSON($fullname));
}

sub readJSON
{
	my $fname=$_[0];
	my $json;
	{
		local $/; #Enable 'slurp' mode
  		open my $fh, "<", "$fname" or die_nice("can't open $fname file to read $!");
  		$json = <$fh>;
  		close $fh;
	}
	while (substr($json, 0, 1) ne "{")
	{
		print " json = [".substr($json,0,10)."]\n";
		substr($json, 0, 1)="";
	}
	return(decode_json($json));

}

sub writeMAP
{
	my $json=$_[0];
	my $fname=$_[1];
	my $realm=get_realm();
    my $fullname=$fname.".".$realm;
	writeJSON($json,$fullname);	
}

sub writeJSON
{
	my $json=$_[0];
    my $fname=$_[1];
	open my $fh, ">", "$fname" or die_nice("can't open $fname file to write $!");
	print $fh encode_json($json);
	close $fh;
}

sub fileREALM
{
	my $fileName=$_[0];
	my ($dum1,$dum2,$realm,$dum3)=split /_/ , $fileName;
	return($realm);
}

sub fdateTime
{
	my $currtime=time;
 	$currtime=$_[0] if defined $_[0];
	$currtime=looks_like_number($currtime)?$currtime:0;
  	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($currtime);
	$year += 1900;
  	$mon  += 1;
  	if ($min  < 10) { $min  = "0$min"};
  	if ($sec  < 10) { $sec  = "0$sec"};
  	if ($hour < 10) { $hour = "0$hour"};
  	if ($mday < 10) { $mday = "0$mday"};
  	if ($mon  < 10) { $mon  = "0$mon"};
  	my $date       = "$year$mon$mday";
  	my $time       = "$hour$min$sec";
  	chomp($date);
  	return($date,$time); 
}

sub pdateTime
{
	my $currtime=time;
 	$currtime=$_[0] if defined $_[0];
	$currtime=looks_like_number($currtime)?$currtime:0;
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($currtime);
	$year += 1900;
  	$mon  += 1;
  	if ($min  < 10) { $min  = "0$min"};
  	if ($sec  < 10) { $sec  = "0$sec"};
  	if ($hour < 10) { $hour = "0$hour"};
  	if ($mday < 10) { $mday = "0$mday"};
  	if ($mon  < 10) { $mon  = "0$mon"};
  	my $date       = "$year/$mon/$mday";
  	my $time       = "$hour:$min:$sec";
  	chomp($date);
  	return($date,$time); 
}

sub pfileDate
{
	my $fileName=$_[0];
	my ($dum1,$dum2,$workstring,$dum3)=split /_/ , $fileName;
	my ($timestring,$dum4)=split /\./ , $workstring;
	return(pdateTime($timestring),$timestring);
}

sub ffileDate
{
	my $fileName=$_[0];
	my ($dum1,$dum2,$workstring,$dum3)=split /_/ , $fileName;
	my ($timestring,$dum4)=split /\./ , $workstring;
	return(fdateTime($timestring));
}

sub numF {
  my $text = reverse $_[0];
  $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
  return scalar reverse $text;
} # Commify

